<!--
Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

https://www.mall4j.com/

未经允许，不可做商业用途！

版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-post-prod">
    <!-- <pord-title :prodTitle="'发布商品'" /> -->

    <!-- 商品名称 -->
    <view class="goods-name">
      <view class="L0">
        <text>
          商品名称<text class="required">
            *
          </text>
        </text>
        <textarea
          v-model="dataForm.prodName"
          type="text"
          :maxlength="60"
          placeholder-style="color:#999"
          placeholder="长度不超过60个字符"
        />
      </view>
      <view class="L1">
        <text>商品卖点</text>
        <textarea
          v-model="dataForm.brief"
          type="text"
          :maxlength="100"
          placeholder-style="color:#999"
          placeholder="长度不超过100个字符"
        />
      </view>
    </view>

    <!-- 上传图片视频 -->
    <view class="goods-img">
      <view class="L0">
        <text>
          商品图片<text class="required">
            *
          </text>
        </text>
        <view
          id="img"
          class="img"
        >
          <htz-image-upload
            ref="imgRef"
            v-model="dataForm.imageData"
            :max="9"
            media-type="image"
            :compress="false"
            name="file"
            :choose-num="1"
            @choose-success="onChooseSuccessImages"
          />
        </view>

        <text class="hint">
          建议尺寸800*800像素，最多上传9张，首图为主图。
        </text>
      </view>
      <view class="L1">
        <text>商品视频</text>
        <view class="img">
          <htz-image-upload
            v-model="dataForm.videoData"
            :max="1"
            :compress="false"
            media-type="video"
            name="file"
            :choose-num="9"
            @choose-success="onChooseSuccessVideo"
          />
        </view>
        <text class="hint">
          主图视频建议时长9-30秒，视频宽高和商品图保持一致。
        </text>
      </view>
    </view>

    <!-- 商品类目 -->
    <view class="goods-type goods">
      <view class="list">
        <view>
          <text>平台类目</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toSelectType(1)"
        >
          <text :class="[selected.categoryName ? 'selected' : '', dataForm.prodId ? 'disable' : '']">
            {{ selected.categoryName ? selected.categoryName : "请选择" }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>店铺类目</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toSelectType(2)"
        >
          <text :class="selected.shopCategoryName ? 'selected' : ''">
            {{ selected.shopCategoryName ? selected.shopCategoryName : "请选择" }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>商品类型</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="moldOpen"
        >
          <text :class="dataForm.mold === null || dataForm.prodId ? '' : 'selected'">
            {{ dataForm.mold === null ? "请选择" : dataForm.mold === 0 ? '实物商品' : '虚拟商品' }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>商品品牌</text>
        </view>
        <view
          class="right"
          @tap="toCommodityBrand"
        >
          <text :class="dataForm.brandName ? 'selected' : ''">
            {{ dataForm.brandName ? dataForm.brandName : "可选填" }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>商品排序</text>
        </view>
        <view class="right">
          <input
            v-model="dataForm.seq"
            type="number"
            placeholder="可选填"
            placeholder-style="color:#999"
            @blur="seqChange"
          >
        </view>
      </view>
      <view
        v-if="(!dataForm.prodId || dataForm.prodType === 5) && dataForm.mold !== 1"
        class="list"
      >
        <view>
          <text>组合选品</text><text class="activity">
            (组合选品不能单独购买)
          </text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :checked="dataForm.prodType == 5"
            :disabled="dataForm.prodId"
            @change="prodTypeChange"
          />
        </view>
      </view>
      <!-- &&(!dataForm.prodId||!dataForm.preSellTime) -->
      <view
        v-if="dataForm.prodType !== 5 && dataForm.mold !== 1"
        class="list"
      >
        <view>
          <text>开启预售</text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :checked="dataForm.preSellStatus == 1"
            @change="preSellStatusChange"
          />
        </view>
      </view>
      <view
        v-if="dataForm.preSellStatus == 1 && dataForm.prodType !== 5 && dataForm.mold !== 1"
        class="list"
      >
        <view>
          <text>预售发货时间</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toPresellTime"
        >
          <text :class="dataForm.preSellTime ? 'selected' : ''">
            {{ dataForm.preSellTime ? preSellTimeShowHandler(dataForm.preSellTime) : '请选择' }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 商品规格 -->
    <view class="goods-type goods">
      <view class="list">
        <view>
          <text>多规格</text>
        </view>
        <view class="uni-padding-wrap uni-common-mt aligning">
          <switch
            color="#082BA6"
            :checked="dataForm.specifications"
            @change="dataForm.specifications = !dataForm.specifications"
          />
        </view>
      </view>
      <view v-if="!dataForm.specifications">
        <view class="list">
          <view>
            <text>销售价格</text><text class="required">
              *
            </text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.price"
              type="number"
              placeholder="请填写"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.price, 'price', 0.01, 100000000)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>市场价格</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.oriPrice"
              type="number"
              placeholder="划线价"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.oriPrice, 'oriPrice', 0, 100000000)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>商品库存</text><text class="required">
              *
            </text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.totalStocks"
              type="number"
              placeholder="请填写"
              placeholder-style="color:#999"
              @blur="numHandleInputValue(dataForm.totalStocks, 'totalStocks', 0, 9999999)"
            >
          </view>
        </view>
        <view
          v-if="dataForm.mold !== 1"
          class="list"
        >
          <view>
            <text>体积(m³)</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.volume"
              type="number"
              placeholder="可选填"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.volume, 'volume', 0, 100000000)"
            >
          </view>
        </view>
        <view
          v-if="dataForm.mold !== 1"
          class="list"
        >
          <view>
            <text>重量(kg)</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.weight"
              type="number"
              placeholder="可选填"
              placeholder-style="color:#999"
              @blur="handleInputValue(dataForm.weight, 'weight', 0, 100000000)"
            >
          </view>
        </view>
        <view class="list">
          <view>
            <text>商品编码</text>
          </view>
          <view class="right">
            <input
              v-model="dataForm.partyCode"
              type="text"
              placeholder="如无编码将自动生成"
              placeholder-style="color:#999"
              @blur="validatePartyCode(dataForm.partyCode)"
            >
          </view>
        </view>
      </view>
      <view v-if="dataForm.specifications">
        <view class="list">
          <view>
            <text>商品规格</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @tap="toSpecificationManagement"
          >
            <text :class="dataForm.skuList.length > 0 ? 'selected' : ''">
              {{ dataForm.skuList.length > 0 ? '已设置' : "请选择" }}
            </text>
            <view class="icon" />
          </view>
        </view>
        <view
          v-if="dataForm.skuList.length > 0"
          class="list"
        >
          <view>
            <text>规格明细</text><text class="required">
              *
            </text>
          </view>
          <view
            class="right"
            @tap="toSpecificationBreakdown"
          >
            <text :class="dataForm.skuList.length > 0 ? 'selected' : ''">
              {{ dataForm.skuList.length > 0 ? '共' + dataForm.skuList.length + '项' : "请选择规格" }}
            </text>
            <view class="icon" />
          </view>
        </view>
      </view>
    </view>

    <!-- 配送 -->
    <view
      v-if="dataForm.prodType !== 5 && dataForm.mold !== 1"
      class="goods-delivery goods"
    >
      <view class="list">
        <view>
          <text>配送方式</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="deliveryModeOpen"
        >
          <text
            :class="dataForm.deliveryModeVo.hasUserPickUp || dataForm.deliveryModeVo.hasShopDelivery || dataForm.deliveryModeVo.hasCityDelivery ? 'selected' : ''"
          >
            {{
              !dataForm.deliveryModeVo.hasUserPickUp && !dataForm.deliveryModeVo.hasShopDelivery && !dataForm.deliveryModeVo.hasCityDelivery ? '请选择' : ''
            }}{{ dataForm.deliveryModeVo.hasShopDelivery ? '快递配送' : '' }}{{ dataForm.deliveryModeVo.hasUserPickUp ? '/用户自提' : ''
            }}{{ dataForm.deliveryModeVo.hasCityDelivery ? '/同城配送' : '' }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>运费设置</text><text class="required">
            *
          </text>
        </view>
        <view
          class="right"
          @tap="toTableRate"
        >
          <text :class="dataForm.deliveryTemplateName ? 'selected' : ''">
            {{ dataForm.deliveryTemplateName ? dataForm.deliveryTemplateName : '请选择' }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 参数 -->
    <view class="goods">
      <view class="list">
        <view>
          <text>参数设置</text>
        </view>
        <view
          class="right"
          @tap="toParameter"
        >
          <text :class="dataForm.prodParameterList.length > 0 ? 'selected' : ''">
            {{ dataForm.prodParameterList.length > 0 ? '共' + dataForm.prodParameterList.length + '组' : '请添加' }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 核销 -->
    <view
      v-if="dataForm.mold === 1"
      class="goods"
    >
      <view class="list">
        <view>
          <text>核销次数</text>
        </view>
        <view
          class="right"
          @tap="toWriteOff"
        >
          <text :class="dataForm.writeOffNum !== null ? 'selected' : ''">
            {{ dataForm.writeOffNum === 1 ? '单次核销' : null }}{{ dataForm.writeOffNum === 0 ? '无需核销' : null }}{{
              dataForm.writeOffNum === -1 ? '多次核销' : null }} {{ dataForm.writeOffNum === null ? '请选择' : null }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>用户留言</text>
        </view>
        <view
          class="right"
          @tap="toMessage"
        >
          <text :class="dataForm.virtualRemark.length > 0 ? 'selected' : ''">
            {{ dataForm.virtualRemark.length > 0 ? '共' + dataForm.virtualRemark.length + '组' : '请添加' }}
          </text>
          <view class="icon" />
        </view>
      </view>
      <view class="list">
        <view>
          <text>售后服务</text>
        </view>
        <view
          class="right"
          @tap="aftersalesOpen"
        >
          <text :class="dataForm.isRefund === 1 || dataForm.isRefund === 0 ? 'selected' : ''">
            {{ dataForm.isRefund !== null ? dataForm.isRefund === 1 ? '支持买家申请退款' : '不支持买家申请退款' : '请选择' }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="goods-details goods">
      <view class="list">
        <view>
          <text>商品详情</text>
        </view>
        <view
          class="right"
          @tap="toCommodityDetails"
        >
          <text :class="dataForm.content ? 'selected' : ''">
            {{ dataForm.content ? "已添加" : "请添加" }}
          </text>
          <view class="icon" />
        </view>
      </view>
    </view>

    <!-- 上架 -->
    <view class="grounding">
      <button
        class="button"
        type="primary"
        @tap="submit"
      >
        {{ dataForm.prodId ? '保存' : '上架出售' }}
      </button>
    </view>

    <!-- 选择商品类型 -->
    <uni-popup
      ref="moldPopupRef"
      type="bottom"
    >
      <view class="optionType">
        <view class="title">
          <text>选择商品类型</text>
          <view
            class="close iconfont"
            @tap="moldClose(1)"
          >
            &#xe60e;
          </view>
        </view>
        <view
          :class="mold === 0 ? 'active list' : 'list'"
          @tap="moleChange(0)"
        >
          <view class="left">
            <text>实物商品</text><text class="hint">
              (物流发货)
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="mold === 1 ? 'active list' : 'list'"
          @tap="moleChange(1)"
        >
          <view class="left">
            <text>虚拟商品</text><text class="hint">
              (无需物流)
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view class="">
          <button
            class="button"
            type="primary"
            @tap="moldClose"
          >
            确定
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 选择配送方式 -->
    <uni-popup
      ref="deliveryModePopupRef"
      type="bottom"
    >
      <view class="optionType">
        <view class="title">
          <text>选择配送方式</text>
          <view
            class="close iconfont"
            @tap="deliveryModeClose(1)"
          >
            &#xe60e;
          </view>
        </view>
        <view class="list active">
          <view class="left">
            <text>快递配送</text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="dataForm.deliveryModeVo.hasUserPickUp ? 'list active' : 'list'"
          @tap="dataForm.deliveryModeVo.hasUserPickUp = !dataForm.deliveryModeVo.hasUserPickUp"
        >
          <view class="left">
            <text>用户自提</text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="[dataForm.deliveryModeVo.hasCityDelivery ? 'active' : '', 'list']"
          @tap="deliveryModeVoChange"
        >
          <view class="left">
            <text :class="sameCityStatus !== 1 ? 'disable' : ''">
              同城配送
            </text><text class="hint">
              (需在PC配送管理设置后生效)
            </text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view class="delivery">
          <button
            class="button"
            type="primary"
            @tap="deliveryModeClose"
          >
            确定
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 售后服务 -->
    <uni-popup
      ref="aftersalesPopupRef"
      type="bottom"
    >
      <view class="optionType">
        <view class="title">
          <text>售后服务</text>
          <view
            class="close iconfont"
            @tap="aftersalesClose(1)"
          >
            &#xe60e;
          </view>
        </view>
        <view
          :class="dataForm.isRefund === 1 ? 'list active' : 'list'"
          @tap="dataForm.isRefund = 1"
        >
          <view class="left">
            <text>支持买家申请退款</text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          :class="[dataForm.isRefund === 0 ? 'active' : '', 'list']"
          @tap="dataForm.isRefund = 0"
        >
          <view class="left">
            <text>不支持买家申请退款</text>
          </view>
          <view class="right iconfont">
            &#xe659;
          </view>
        </view>
        <view
          v-if="dataForm.isRefund === 0"
          class="text"
        >
          提示：选择“不支持买家申请退款”，商品详情页将展示“不支持申请退款”的说明，买家如需退款只能主动联系商家处理
        </view>
        <view class="delivery">
          <button
            class="button"
            type="primary"
            @tap="aftersalesClose()"
          >
            确定
          </button>
        </view>
      </view>
    </uni-popup>
    <helang-compress ref="helangCompressRef" />
  </view>
</template>

<script setup>
import { validNoEmptySpace } from '@/utils/validate'
import util from '../../../utils/util'

const Data = reactive({
  sameCityStatus: null,
  isSubmit: true,
  isNullLen: 0,
  mold: null,
  masterLang: null
})

const { sameCityStatus, mold } = toRefs(Data)

const prodStore = useProdStore()

const dataForm = computed(() => {
  return prodStore.dataForm
})

const selected = computed(() => {
  return prodStore.selected
})

onLoad((options) => {
  if (options.prodId || options.add) {
    uni.removeStorageSync('bbcProdDataFrom')
    prodStore.resetForm()
  }
  getProdInfo(options.prodId)
  getSameCityDetail()
})

onShow(() => {
  const router = getCurrentPages()
  if (router[router.length - 2]?.route === '/package-prod/pages/prod-management/prod-management' && !(router[router.length - 1].options.add) && !(router[router.length - 1].options.prodId)) {
    uni.navigateTo({
      url: 'pages/index/index'
    })
  }

  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: prodStore.scroll,
      duration: 0
    })
  }, 0)
})

onHide(() => {
  // #ifdef H5
  prodStore.scroll = document.documentElement.scrollTop
  // #endif
})

const getLangList = () => {
  http.request({
    url: '/sys/lang',
    method: 'GET',
    data: {
    }
  }).then(({ data: res }) => {
    // console.log('国际化语言列表', res)
    if (!prodStore.dataForm.prodId) {
      Data.masterLang = res.lang
      prodStore.dataForm.prodLangList = [{
        prodId: 0,
        lang: res.lang,
        prodName: '',
        brief: '',
        content: ''
      }]
    } else {
      for (const item of prodStore.dataForm.prodLangList) {
        if (item.prodName === prodStore.dataForm.prodName) {
          Data.masterLang = item.lang
          break
        }
      }
    }
  })
}

// 数据反显
const getProdInfo = (prodId) => {
  if (prodId) {
    http.request({
      url: `/prod/prod/info/${prodId}`,
      method: 'GET',
      data: {
      }
    }).then(({ data: res }) => {
      res.deliveryModeVo = JSON.parse(res.deliveryMode)
      res.deliveryMode = JSON.parse(res.deliveryMode)
      res.virtualRemark = res.virtualRemark ? JSON.parse(res.virtualRemark) : []
      prodStore.dataForm = {
        ...prodStore.dataForm,
        ...res,
        changeStock: res.totalStocks
      }
      prodStore.dataForm.skuList.forEach(x => {
        x.changeStock = 0
      })
      if (!prodStore.dataForm.preSellTime) {
        prodStore.dataForm.preSellTime = ''
      }
      if (prodStore.dataForm.skuList.length === 1 && prodStore.dataForm.skuList[0].properties === '') { // 单规格处理
        prodStore.dataForm.specifications = false
        prodStore.dataForm.volume = prodStore.dataForm.skuList[0].volume
        prodStore.dataForm.partyCode = prodStore.dataForm.skuList[0].partyCode
        prodStore.dataForm.weight = prodStore.dataForm.skuList[0].weight
        prodStore.dataForm.skuId = prodStore.dataForm.skuList[0].skuId
      } else { // 多规格处理
        prodStore.dataForm.specifications = true
      }
      if (prodStore.dataForm.imgs) prodStore.dataForm.imageData = prodStore.dataForm.imgs.split(',')
      if (prodStore.dataForm.video) prodStore.dataForm.videoData = prodStore.dataForm.video.split(',')
      if (prodStore.dataForm.brand) prodStore.dataForm.brandName = prodStore.dataForm.brand.name

      // 运费反显
      // 统一包邮
      if (prodStore.dataForm.deliveryTemplateId === 0) {
        prodStore.dataForm.deliveryTemplateName = '统一包邮'
        prodStore.deliveryIndex.index = 1
      }
      // 统一运费
      if (prodStore.dataForm.deliveryTemplateId === -1) {
        prodStore.dataForm.deliveryTemplateName = prodStore.dataForm.deliveryAmount + '元'
        prodStore.deliveryIndex.pic = prodStore.dataForm.deliveryAmount
        prodStore.deliveryIndex.index = 2
      }
      // 运费模板
      if (prodStore.dataForm.deliveryTemplateId > 0) {
        prodStore.deliveryIndex.id = prodStore.dataForm.deliveryTemplateId
        prodStore.deliveryIndex.index = 3
        getdeliveryTemplateName()
      }
      getCategoryName()
      getLangList()
    })
  } else {
    getLangList()
  }
}

/**
* 只允许输入正数和小数(保留小数点后两位)
*/
const checkInput = (num) => {
  if (num) {
    let tmpVal = String(num).replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

// 获取分类名称
const getCategoryName = () => {
  http.request({
    url: '/prod/category/listAvailableSigningCategory',
    method: 'GET',
    data: {

    }
  }).then(({ data: res }) => {
    prodStore.dataForm.classifyName[2] = (res.filter(item => item.categoryId === prodStore.dataForm.categoryId))[0]
    prodStore.dataForm.classifyName[1] = (res.filter(item => item.categoryId === prodStore.dataForm.classifyName[2].parentId))[0]
    prodStore.dataForm.classifyName[0] = (res.filter(item => item.categoryId === prodStore.dataForm.classifyName[1].parentId))[0]
    prodStore.selected.categoryName = prodStore.dataForm.classifyName[0].categoryName + '/' + prodStore.dataForm.classifyName[1].categoryName + '/' + prodStore.dataForm.classifyName[2].categoryName
    getShopTypeName()
  })
}

// 获取运费模板名称
const getdeliveryTemplateName = () => {
  if (!prodStore.dataForm.deliveryTemplateId) {
    return
  }

  http.request({
    url: `/shop/transport/info/${prodStore.dataForm.deliveryTemplateId}`,
    method: 'GET',
    data: {}
  }).then(({ data: res }) => {
    prodStore.dataForm.deliveryTemplateName = res.transName
    prodStore.deliveryIndex.name = res.transName
  })
}

// 获取店铺同城配送的配置
const getSameCityDetail = () => {
  http.request({
    url: '/delivery/sameCity/getSameCityInfo',
    method: 'GET',
    data: {}
  }).then(({ data }) => {
    if (data) {
      prodStore.sameCityStatus = data.status
    }
  })
}

// 获取店铺类目名称
const getShopTypeName = () => {
  http.request({
    url: '/prod/category/listCategory',
    method: 'GET',
    data: {
      status: 1
    }
  }).then(({ data: res }) => {
    prodStore.selected.shopCategoryName = (res.filter(item => item.categoryId === prodStore.dataForm.shopCategoryId))[0].categoryName
  })
}

// 商品排序
const seqChange = (e) => {
  if (e.detail.value) {
    prodStore.dataForm.seq = Math.floor(e.detail.value)
    if (prodStore.dataForm.seq > 32767) {
      prodStore.dataForm.seq = 32767
    }
  }
}

/**
* 处理输入框数据
* @param data
* @param dataFields
* @param min 最小值
* @param max 最大值
*/
const handleInputValue = (data, dataFields, min, max) => {
  if (dataFields !== 'totalStocks') {
    data = parseFloat(data)
  }
  prodStore.dataForm.dataFields = checkInput(data)
  if (data || data === 0) {
    // 保留两位小数
    if (data > max) {
      prodStore.dataForm.dataFields = max
    }
    if (data <= min) {
      prodStore.dataForm.dataFields = min
    }
  }
  if (isNaN(data)) {
    prodStore.dataForm.dataFields = 0
  }
}

// 整数
const numHandleInputValue = (data, dataFields, min, max) => {
  handleInputValue(Math.floor(data), dataFields, min, max)
}

const deliveryModeVoChange = () => {
  if (Data.sameCityStatus === 1) {
    prodStore.dataForm.deliveryModeVo.hasCityDelivery = !prodStore.dataForm.deliveryModeVo.hasCityDelivery
  }
}

/**
* 编码输入框校验
*/
const validatePartyCode = (partyCode) => {
  // 纯空格校验
  if (validNoEmptySpace(partyCode)) {
    prodStore.dataForm.partyCode = ''
  }
}

const verifySubmot = () => {
  if (!prodStore.dataForm.prodName) {
    uni.showToast({
      title: '请输入商品名称',
      icon: 'none'
    })
    return true
  }

  if (prodStore.dataForm.imageData.length < 1) {
    uni.showToast({
      title: '请选择商品图片',
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.categoryId == null) {
    uni.showToast({
      title: '请选择平台类目',
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.shopCategoryId == null) {
    uni.showToast({
      title: '请选择店铺类目',
      icon: 'none'
    })
    return true
  }
  if (prodStore.dataForm.mold === null) {
    // 请选择商品分类
    uni.showToast({
      title: '请选择商品类型',
      icon: 'none'
    })
    return true
  }

  if (prodStore.dataForm.preSellStatus === 1 && !prodStore.dataForm.preSellTime) {
    // 请选择商品分类
    uni.showToast({
      title: '请选择预售发货时间',
      icon: 'none'
    })
    return true
  }

  // 单规格效验
  if (!prodStore.dataForm.specifications) {
    if (!prodStore.dataForm.price) {
      uni.showToast({
        title: '请输入销售价格',
        icon: 'none'
      })
      return true
    }
    if (prodStore.dataForm.totalStocks === '') {
      uni.showToast({
        title: '请输入商品库存',
        icon: 'none'
      })
      return true
    }
  } else { // 多规格效验
    if (prodStore.dataForm.skuList.length < 1) {
      uni.showToast({
        title: '请选择商品规格',
        icon: 'none'
      })
      return true
    }
  }
  if (prodStore.dataForm.deliveryTemplateId === null && prodStore.dataForm.prodType !== 5 && prodStore.dataForm.mold !== 1) {
    uni.showToast({
      title: '请选择运费',
      icon: 'none'
    })
    return true
  }

  let isStatusLen = 0
  prodStore.dataForm.skuList.forEach(item => {
    if (item.status === 0) {
      isStatusLen++
    }
  })
  if (isStatusLen === prodStore.dataForm.skuList.length && prodStore.dataForm.specifications) {
    uni.showToast({
      title: '至少要启用一种商品规格',
      icon: 'none'
    })
    return true
  }
  return false
}

// 提交发布或修改
const submit = () => {
  if (verifySubmot() || !Data.isSubmit) {
    return
  }

  // 提交前的数据处理
  dataAlignment()

  let data = JSON.parse(JSON.stringify(prodStore.dataForm))

  // 虚拟商品
  if (data.mold === 1) {
    // 选择"无需核销"，没有核销有效期
    if (data.writeOffNum === 0) {
      data.writeOffTime = null
    }
    // 自定义核销有效天数
    // if (data.writeOffNum !== 0 && data.writeOffTime === 2) {
    //   data.writeOffTime = parseInt(prodStore.validDays)
    // }
    data.virtualRemark = JSON.stringify(data.virtualRemark)
    // 取消组合选品，预售，配送方式,运费模板
    data.prodType = 0
    data.preSellStatus = 0
    data.preSellTime = ''
    data.deliveryModeVo.hasUserPickUp = false
    data.deliveryModeVo.hasShopDelivery = true
    data.deliveryModeVo.hasCityDelivery = false
    data.deliveryTemplateId = null
    data.deliveryTemplateName = ''
    data.weight = null
    data.volume = null
  }
  if (data.mold !== 1) {
    // 普通商品，清空虚拟商品信息
    data = {
      ...data,
      virtualRemark: null,
      writeOffNum: null,
      writeOffTime: null,
      writeOffStart: null,
      writeOffEnd: null,
      isRefund: null
    }
    // 组合选品
    if (data.prodType === 5) {
      // 取消预售，配送
      data.preSellStatus = 0
      data.preSellTime = ''
      data.deliveryModeVo.hasUserPickUp = false
      data.deliveryModeVo.hasShopDelivery = true
      data.deliveryModeVo.hasCityDelivery = false
      data.deliveryTemplateId = null
      data.deliveryTemplateName = ''
    }
  }

  if ((!prodStore.dataForm.specifications && prodStore.dataForm.totalStocks === 0) || (prodStore.dataForm.specifications && Data.isNullLen === prodStore.dataForm.skuList.length)) {
    uni.showModal({
      content: '该商品库存为0，确认保存？',
      icon: 'none',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          Data.isSubmit = false
          http.request({
            url: '/prod/prod',
            method: prodStore.dataForm.prodId ? 'PUT' : 'POST',
            data
          }).then(() => {
            uni.showToast({
              title: prodStore.dataForm.prodId ? '修改成功' : '发布成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.reLaunch({
                url: '/package-prod/pages/prod-management/prod-management'
              })
            }, 1500)
          })
          setTimeout(() => {
            Data.isSubmit = true
          }, 2000)
        }
      }
    })
  } else {
    Data.isSubmit = false

    http.request({
      url: '/prod/prod',
      method: prodStore.dataForm.prodId ? 'PUT' : 'POST',
      data
    }).then(() => {
      uni.showToast({
        title: prodStore.dataForm.prodId ? '修改成功' : '发布成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/package-prod/pages/prod-management/prod-management'
        })
      }, 1500)
    })
    setTimeout(() => {
      Data.isSubmit = true
    }, 2000)
  }
}

// 提交前的数据处理
const dataAlignment = () => {
  Data.isNullLen = 0
  // 图片视频格式处理
  prodStore.dataForm.deliveryMode = null
  prodStore.dataForm.imgs = prodStore.dataForm.imageData.join(',')
  prodStore.dataForm.video = prodStore.dataForm.videoData.join(',')
  prodStore.dataForm.pic = prodStore.dataForm.imageData[0]

  // 当前商品语言列表信息是否存在主语言
  const isExistMasterLang = prodStore.dataForm.prodLangList.find(f => Data.masterLang === f.lang)
  // 多语言名称处理
  prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => {
    prodLang.prodId = prodStore.dataForm.prodId || 0
    if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
      prodLang.prodName = prodStore.dataForm.prodName
      prodLang.brief = prodStore.dataForm.brief
      prodLang.content = prodStore.dataForm.content
    } else {
      prodLang.prodName = prodLang.prodName || prodStore.dataForm.prodName
      prodLang.brief = prodLang.brief || prodStore.dataForm.brief
      prodLang.content = prodLang.content || prodStore.dataForm.content
    }
  })

  if (prodStore.dataForm.specifications) { // 多规格处理
    prodStore.dataForm.price = ''
    prodStore.dataForm.skuList.forEach((item, index) => {
      const skuLangList = []
      prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => {
        const findR = item.skuLangList?.find(f => f.lang === prodLang.lang) || {}
        if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
          skuLangList.push({
            skuId: item.skuId || 0,
            lang: prodLang.lang,
            properties: item.properties,
            skuName: item.skuName,
            prodName: item.prodName
          })
        } else {
          skuLangList.push({
            skuId: item.skuId || 0,
            lang: findR.lang || prodLang.lang,
            properties: findR.properties || item.properties,
            skuName: findR.skuName || item.skuName,
            prodName: findR.prodName || item.prodName
          })
        }
      })
      item.skuLangList = skuLangList
      if (!prodStore.dataForm.price && item.status === 1) {
        prodStore.dataForm.price = item.price
      }
      // if (index === 0 || prodStore.dataForm.price > item.price) {
      //   prodStore.dataForm.price = item.price
      // }

      if (index === 0 || prodStore.dataForm.oriPrice < item.oriPrice) {
        prodStore.dataForm.oriPrice = item.oriPrice
      }

      if (index === 0) {
        prodStore.dataForm.totalStocks = item.stocks
      } else {
        prodStore.dataForm.totalStocks += item.stocks
      }

      if (item.stocks === 0) {
        Data.isNullLen++
      }
    })
  } else { // 单规格处理
    prodStore.dataForm.oriPrice = prodStore.dataForm.oriPrice || 0
    prodStore.dataForm.skuList = []
    const skuLangList = []
    prodStore.dataForm.prodLangList.forEach(prodLang => {
      skuLangList.push({
        skuId: prodStore.dataForm.skuId || 0,
        lang: prodLang.lang,
        properties: '',
        skuName: '',
        prodName: prodStore.dataForm.prodName
      })
    })
    prodStore.dataForm.skuList[0] = {
      changeStock: prodStore.dataForm.totalStocks - prodStore.dataForm.changeStock,
      oriPrice: prodStore.dataForm.oriPrice,
      partyCode: prodStore.dataForm.partyCode,
      price: prodStore.dataForm.price,
      prodName: prodStore.dataForm.prodName,
      skuId: prodStore.dataForm.skuId,
      properties: '',
      skuName: '',
      status: 1,
      stocks: prodStore.dataForm.totalStocks,
      volume: prodStore.dataForm.volume,
      weight: prodStore.dataForm.weight,
      skuLangList
    }
  }

  // 如果sku没有商品名称，则使用商品的商品名称
  if (prodStore.dataForm.skuList.length === 1 && !prodStore.dataForm.skuList[0].skuName) {
    prodStore.dataForm.skuList[0].prodName = prodStore.dataForm.prodName
  }

  // 多语言参数设置
  prodStore.dataForm.prodParameterList.forEach(parame => {
    parame.prodParameterId = parame.prodParameterId || 0
    parame.prodId = prodStore.dataForm.prodId || 0
    const prodParameterLangList = []
    prodStore.dataForm.prodLangList.forEach((prodLang, prodInx) => {
      const findR = parame.prodParameterLangList?.find(f => f.lang === prodLang.lang) || {}
      if ((isExistMasterLang && Data.masterLang === prodLang.lang) || (!isExistMasterLang && prodInx === 0)) {
        prodParameterLangList.push({
          prodParameterId: findR.prodParameterId || parame.prodParameterId || 0,
          lang: prodLang.lang,
          parameterKey: parame.parameterKey,
          parameterValue: parame.parameterValue
        })
      } else {
        prodParameterLangList.push({
          prodParameterId: findR.prodParameterId || parame.prodParameterId || 0,
          lang: prodLang.lang,
          parameterKey: findR.parameterKey || parame.parameterKey,
          parameterValue: findR.parameterValue || parame.parameterValue
        })
      }
    })
    parame.prodParameterLangList = prodParameterLangList
  })
}

const helangCompressRef = ref()
const onChooseSuccessImages = (tempFilePaths, e) => { // 选择图片返回
  let arr = []
  let str = ''
  // #ifdef H5
  arr = e.tempFiles[0].name.split('.')
  // #endif
  // #ifdef MP-WEIXIN
  arr = e.tempFiles[0].path.split('.')
  // #endif
  // #ifdef APP-PLUS
  arr = tempFilePaths[0].split('.')
  // #endif
  str = arr[arr.length - 1]
  if (str !== 'png' && str !== 'jpg' && str !== 'gif' && str !== 'jpeg') {
    uni.showToast({
      title: '图片格式仅支持jpg/png/gif/jpeg',
      icon: 'none'
    })
    return
  }
  uni.showLoading({
    mask: true
  })
  const obj = {
    src: tempFilePaths[tempFilePaths.length - 1],
    quality: 0.2
  }

  helangCompressRef.value.compress(obj, tempFilePaths[0]).then(res => {
    // #ifdef H5
    http.request({
      url: '/admin/file/getPreSignUrl',
      method: 'GET',
      data: { fileName: e.tempFiles[0].name, isImFile: false }
    }).then(({ data }) => {
      uni.request({
        url: res,
        method: 'GET',
        responseType: 'arraybuffer',
        success: function (requestRes) {
          uni.request({
            url: data.preSignUrl,
            method: 'PUT',
            data: requestRes.data,
            success: function () {
              http.request({
                url: '/admin/file/uploadSuccess',
                method: 'PUT',
                data: [
                  {
                    fileId: data.fileId,
                    attachFileGroupId: 0,
                    type: 1,
                    fileSize: e.tempFiles[0].size
                  }
                ]
              }).then(() => {
                imgUpload(data.fileId, 1)
              })
            }
          })
        }
      })
    })
    // #endif
    // #ifdef APP-PLUS
    http.request({
      url: '/admin/file/getPreSignUrl',
      method: 'GET',
      data: { fileName: tempFilePaths[0], isImFile: false }
    }).then(({ data }) => {
      util.plusIo(res).then((buffer) => {
        uni.request({
          url: data.preSignUrl,
          method: 'PUT',
          data: buffer,
          success: function () {
            http.request({
              url: '/admin/file/uploadSuccess',
              method: 'PUT',
              data: [
                {
                  fileId: data.fileId,
                  attachFileGroupId: 0,
                  type: 1
                }
              ]
            }).then(() => {
              imgUpload(data.fileId, 1)
            })
          }
        })
      })
    })
    // #endif
  })
}

const onChooseSuccessVideo = (tempFilePaths, e) => { // 选择视频返回
  let arr = []
  let str = ''
  let size = 0
  let filePath = ''
  // #ifdef H5
  arr = e.tempFile.name.split('.')
  size = e.tempFile.size
  filePath = tempFilePaths[tempFilePaths.length - 1]
  // #endif

  // #ifdef APP-PLUS
  arr = tempFilePaths[0].split('.')
  size = e.size
  filePath = e.tempFilePath
  // #endif
  str = arr[arr.length - 1]

  if (str !== 'mp4' && str !== 'mov' && str !== 'webm') {
    uni.showToast({
      title: '视频格式仅支持mp4/mov/webm',
      icon: 'none'
    })
    return
  }
  if (size > 20971520) {
    uni.showToast({
      title: '视频大小不能超过20M',
      icon: 'none'
    })
    return
  }
  uni.showLoading({
    mask: true
  })
  // #ifdef H5
  http.request({
    url: '/admin/file/getPreSignUrl',
    method: 'GET',
    data: { fileName: e.tempFile.name, isImFile: false }
  }).then(({ data }) => {
    uni.request({
      url: filePath,
      method: 'GET',
      responseType: 'arraybuffer',
      success: function (requestRes) {
        uni.request({
          url: data.preSignUrl,
          method: 'PUT',
          data: requestRes.data,
          success: function () {
            http.request({
              url: '/admin/file/uploadSuccess',
              method: 'PUT',
              data: [
                {
                  fileId: data.fileId,
                  attachFileGroupId: 0,
                  type: 2,
                  fileSize: e.tempFile.size
                }
              ]
            }).then(() => {
              imgUpload(data.fileId, 2)
            })
          }
        })
      }
    })
  })
  // #endif
  // #ifdef APP-PLUS
  http.request({
    url: '/admin/file/getPreSignUrl',
    method: 'GET',
    data: { fileName: tempFilePaths[0], isImFile: false }
  }).then(({ data }) => {
    util.plusIo(tempFilePaths[0]).then((buffer) => {
      uni.request({
        url: data.preSignUrl,
        method: 'PUT',
        data: buffer,
        success: function () {
          http.request({
            url: '/admin/file/uploadSuccess',
            method: 'PUT',
            data: [
              {
                fileId: data.fileId,
                attachFileGroupId: 0,
                type: 2
              }
            ]
          }).then(() => {
            imgUpload(data.fileId, 2)
          })
        }
      })
    })
  })
  // #endif
}

const imgUpload = (data, index) => {
  uni.showLoading({
    title: '上传中'
  })
  http.request({
    url: '/admin/file/attachFilePage',
    method: 'get',
    data: {
      fileId: data,
      current: 1,
      size: 1,
      type: index
    }
  }).then(({ data }) => {
    if (index === 1) {
      prodStore.dataForm.imageData.push(data.records[0].filePath)
      // console.log(prodStore.dataForm.imageData)
    } else if (index === 2) {
      prodStore.dataForm.videoData.push(data.records[0].filePath)
    }
    uni.hideLoading()
    // #ifdef H5
    // 添加图片后滚动条滑到到最后
    setTimeout(() => {
      const img = document.getElementById('img')
      img.scrollLeft = img.scrollWidth - img.offsetWidth
    }, 0)
    // #endif
  })
}

// 是否预售
const preSellStatusChange = (e) => {
  e.detail.value ? prodStore.dataForm.preSellStatus = 1 : prodStore.dataForm.preSellStatus = 0
}

// 是否组合选品
const prodTypeChange = (e) => {
  e.detail.value ? prodStore.dataForm.prodType = 5 : prodStore.dataForm.prodType = 0
}

const moldPopupRef = ref()
// 商品类型弹出层
const moldOpen = () => {
  if (prodStore.dataForm.prodId) {
    uni.showToast({
      title: '已发布的商品不允许修改商品类型',
      icon: 'none'
    })
    return
  }
  Data.mold = prodStore.dataForm.mold
  moldPopupRef.value.open('share')
}

const moleChange = (num) => {
  Data.mold = num
}

// type 1为取消这次选择
const moldClose = (type) => {
  if (type !== 1) {
    prodStore.dataForm.mold = Data.mold
  }
  moldPopupRef.value.close()
}

const deliveryModePopupRef = ref()
// 打开配送方式弹出层
const deliveryModeOpen = () => {
  prodStore.cacheDeliveryMode = JSON.parse(JSON.stringify(prodStore.dataForm.deliveryModeVo))
  deliveryModePopupRef.value.open('share')
}

// 关闭配送方式弹出层
const deliveryModeClose = (type) => {
  if (type === 1) {
    prodStore.dataForm.deliveryModeVo = prodStore.cacheDeliveryMode
  }
  deliveryModePopupRef.value.close()
}

const aftersalesPopupRef = ref()
// 打开售后服务弹出层
const aftersalesOpen = () => {
  prodStore.isRefund = JSON.parse(JSON.stringify(prodStore.dataForm.isRefund))
  aftersalesPopupRef.value.open('share')
}

// 关闭售后服务弹出层
const aftersalesClose = (type) => {
  if (type === 1) {
    prodStore.dataForm.isRefund = prodStore.isRefund
  }
  aftersalesPopupRef.value.close()
}

// 选择商品类目
const toSelectType = (value) => {
  if (value === 1 && prodStore.dataForm.prodId) {
    uni.showToast({
      title: '已发布的商品不允许修改平台分类',
      icon: 'none'
    })
    return
  }
  prodStore.dataForm.selectType = value
  uni.navigateTo({
    url: '/package-prod/pages/select-type/select-type'
  })
}

// 选择品牌
const toCommodityBrand = () => {
  if (!prodStore.dataForm.categoryId) {
    uni.showToast({
      title: '请先选择商品类目',
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/commodity-brand'
  })
}

// 选择预售时间
const toPresellTime = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/presell-time'
  })
}

// 选择规格
const toSpecificationManagement = () => {
  uni.navigateTo({
    url: '/package-prod/pages/specification-management/specification-management'
  })
}
// 规格明细
const toSpecificationBreakdown = () => {
  uni.navigateTo({
    url: '/package-prod/pages/specification-breakdown/specification-breakdown'
  })
}
// 运费模板
const toTableRate = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/table-rate'
  })
}
// 商品详情
const toCommodityDetails = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/commodity-details'
  })
}
// 参数设置
const toParameter = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-parameter'
  })
}
// 用户留言
const toMessage = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-message'
  })
}
// 核销
const toWriteOff = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/prod-write-off'
  })
}

/**
 * 预售时间显示为 ’YYYY-MM-DD‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  return val.slice(0, -8).trim()
}
</script>

<style lang="scss" scoped>
@use "post-prod";
</style>
